// 处理用户相关的action
// import axios from "axios"
import * as types from "../actionType"
import { setToken as setTokenLocal, clearToken } from "@/utils/auth"
import http from "@/utils/http"

export const setToken = (payload) => ({ type: types.SET_TOKEN, payload })

export const updateUser = (payload) => ({
    type: types.UPDATE_USERINFO,
    payload,
})

export const loginAction = (data) => {
    return async (dispatch) => {
        // 发起异步请求
        // console.log(dispatch);
        const { data: { token } } = await http.post("/v1_0/authorizations", data)
        // console.log(token);
        setTokenLocal(token)
        dispatch(setToken(token))
    }
}

export const getUserInfo = () => {
    return async (dispatch) => {
        // 异步请求
        const { data } = await http.get("/v1_0/user/profile")
        // console.log(data)
        dispatch(updateUser(data))
    }
}

export const logoutAction = () => {
    return (dispatch) => {
        // 删除本地缓存
        clearToken() // 清空本地缓存
        dispatch(setToken("")) // 清空redux中的token
        dispatch(updateUser({})) // 清空用户信息
    }
}